package woaini.wind.bot.job.qylc;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import woaini.wind.bot.core.event.segment.Messages;
import woaini.wind.bot.core.internal.Internal;
import woaini.wind.bot.core.manager.BotManager;

@RestController
@RequestMapping("/qylc/")
@Slf4j
public class QylcWebHook {

  @RequestMapping("/hook")
  public void hook(@RequestBody JSONObject event){
    log.info("qylcHook:{}",event.toJSONString());

    StringBuilder itemBuilder = new StringBuilder();

    JSONArray items = event.getJSONArray("items");
    for (int i = 0; i < items.size(); i++) {
      JSONObject jsonObject = items.getJSONObject(i);

      StringBuilder itemTmpBuilder = new StringBuilder();
      String mod = jsonObject.getString("mod");
      if (StrUtil.isNotBlank(mod)){
        itemTmpBuilder.append(STR."模块:\{mod}").append("\r\n");
      }
      String params = jsonObject.getString("params");
      if (StrUtil.isNotBlank(params)){
        itemTmpBuilder.append(STR."信息:\{params}").append("\r\n");
      }
      Long count = jsonObject.getLong("count");
      if (ObjectUtil.isNull(count)){
        itemTmpBuilder.append(STR."次数:\{count}").append("\r\n");
      }
      itemBuilder.append(itemTmpBuilder).append("\r\n");
    }

    StringBuilder mainBuilder = new StringBuilder();
    mainBuilder.append(STR."--\{event.getString("title")}--").append("\r\n");
    mainBuilder.append(STR."平台:\{event.getString("platform")}").append("\r\n");
    mainBuilder.append(STR."预警级别: \{event.getString("openWaringLevel")}").append("\r\n");
    mainBuilder.append(STR."时间:\{DateUtil.format(event.getDate("createTime"),"yyyy-MM-dd HH:mm:ss")}").append("\r\n");
    mainBuilder.append(STR."描述:\{event.getString("content")}").append("\r\n");
    String link = event.getString("link");
    if (StrUtil.isNotBlank(link)){
      mainBuilder.append(STR."链接:\{event.getString("link")}").append("\r\n");
    }
    mainBuilder.append(STR."处理建议:\{event.getString("handlingSuggestion")}").append("\r\n");
    mainBuilder.append(STR."详情:").append("\r\n");
    mainBuilder.append(itemBuilder);

    System.out.println(mainBuilder);
    Internal internal = BotManager.getBot("李风儿", "wx").internal();
    internal.sendGroupMessage("黔云中台运维", Messages.builder().text(mainBuilder.toString()));
  }
}
